package net.xt.testthread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class TestCountDownLaunch {

    public static void main(String[] args) {
        // 定义最大线程数为5
        CountDownLatch countDownLatch = new CountDownLatch(5);

        IntStream.rangeClosed(1, 5).forEach(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "执行业务操作");

                // 每个线程执行完，countDownLatch数量-1
                countDownLatch.countDown();
            }).start();
        });

        try {
            // 等待上面所有线程全部执行完，主线程再执行
            countDownLatch.await();

            System.out.println(Thread.currentThread().getName() + "执行业务操作");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
